use rand::Rng;
use crate::serviceimpl::init_db;
use sqlx::Error;
pub async fn generate_salt() -> Result<String, Error>{
	let mut salt = pure_generate_salt().await.unwrap();
	while unique_salt(salt.clone()).await.unwrap() == false {
		salt = pure_generate_salt().await.unwrap();
	}
	Ok(salt.clone())
}

pub async fn pure_generate_salt() -> Result<String, Error>{
	let mut salt = "".to_string();
	let saltletters = vec!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
	let mut rng = rand::thread_rng();

	for _i in 0..32 {
		let rand_num: usize = rng.gen_range(0..16);
		salt.push(*saltletters.get(rand_num).unwrap());
	}
	Ok(salt)
}

pub async fn unique_salt(salt:String) ->Result<bool, Error>{
	let app_state = init_db();
	let count = app_state.await.context.users.count_salt(salt).await.unwrap().count_num;
	Ok(count==0)
}
